import { Request, Response, NextFunction } from 'express';

/**
 * 自定义应用错误类
 */
export class AppError extends Error {
  statusCode: number;
  isOperational: boolean;

  constructor(message: string, statusCode: number) {
    super(message);
    this.statusCode = statusCode;
    this.isOperational = true;

    Error.captureStackTrace(this, this.constructor);
  }
}

/**
 * 404 错误处理中间件
 */
export const notFound = (req: Request, res: Response, next: NextFunction) => {
  const error = new AppError(`无法找到 ${req.originalUrl}`, 404);
  next(error);
};

/**
 * 全局错误处理中间件
 */
export const errorHandler = (
  err: AppError,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  let error = { ...err };
  error.message = err.message;

  // 默认错误
  let statusCode = error.statusCode || 500;
  let message = error.message || '服务器内部错误';

  // 开发环境返回详细错误信息
  if (process.env.NODE_ENV === 'development') {
    console.error('错误详情:', {
      message: err.message,
      stack: err.stack,
      statusCode: statusCode
    });
  }

  // 生产环境隐藏敏感信息
  if (process.env.NODE_ENV === 'production') {
    if (statusCode === 500) {
      message = '服务器内部错误';
    }
  }

  res.status(statusCode).json({
    code: statusCode,
    message: message,
    ...(process.env.NODE_ENV === 'development' && { stack: err.stack }),
    timestamp: new Date().toISOString()
  });
};